#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <strings.h>
#include <cstdlib>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using std::cout;
using std::endl;

//./udpclient serveip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cout << "\n\rUsage: " << argv[0] << "serveip serverport\n"<< endl;
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);//主机转网络
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    socklen_t len = sizeof(server);
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        cout << "socker error" << endl;
        return 1;
    }

    // client
    // 首次发送数据的时候，系统就给bind
    std::string message;
    char buffer[1024];
    while (true)
    {
        cout << "Please Enter: ";
        getline(std::cin, message);
        //std::cout<<message<<endl;

        // 1.发数据，给谁发，
        sendto(sockfd, message.c_str(), message.size(), 0, (sockaddr *)&server, len);
        struct sockaddr_in temp;
        socklen_t tlen = sizeof(temp);
        size_t s = recvfrom(sockfd,buffer,1023,0,(sockaddr*)&temp,&tlen);
        if(s>0)
        {
            buffer[s] = 0;
            cout<<buffer<<endl;
        }
    }

    close(sockfd);
    return 0;
}